@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)

package wang.xinqiu.mysqlcontrol.ui

import android.content.Intent
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import wang.xinqiu.mysqlcontrol.data.ConnectionInfo
import wang.xinqiu.mysqlcontrol.data.MySQLManager
import wang.xinqiu.mysqlcontrol.data.QueryResult
import androidx.compose.ui.text.input.TextFieldValue
import wang.xinqiu.mysqlcontrol.data.PreferencesManager
import wang.xinqiu.mysqlcontrol.data.UserPreferences
import wang.xinqiu.mysqlcontrol.data.SmartErrorHandler
import wang.xinqiu.mysqlcontrol.data.SmartSQLHelper
import wang.xinqiu.mysqlcontrol.data.SQLSuggestion
import wang.xinqiu.mysqlcontrol.data.PerformanceMonitor
import wang.xinqiu.mysqlcontrol.data.QueryCache
import wang.xinqiu.mysqlcontrol.data.DataExporter
import wang.xinqiu.mysqlcontrol.data.ErrorHandlingResult
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.border
import kotlinx.coroutines.delay
import wang.xinqiu.mysqlcontrol.data.QueryTemplate
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.compose.rememberLauncherForActivityResult
import wang.xinqiu.mysqlcontrol.data.ExportPath

@Composable
fun QueryScreen(
    connectionInfo: ConnectionInfo,
    databaseName: String,
    mysqlManager: MySQLManager,
    onBack: () -> Unit,
    onSessionExpired: (() -> Unit)? = null
) {
    val context = LocalContext.current
    val preferencesManager: PreferencesManager = remember { PreferencesManager(context) }
    val userPreferences: UserPreferences = remember { UserPreferences(context) }
    val smartErrorHandler: SmartErrorHandler = remember { SmartErrorHandler() }
    val smartSQLHelper: SmartSQLHelper = remember { SmartSQLHelper() }
    val performanceMonitor: PerformanceMonitor = remember { PerformanceMonitor() }
    val queryCache: QueryCache = remember { QueryCache() }
    val dataExporter: DataExporter = remember { DataExporter() }
    
    var sqlQuery by remember { mutableStateOf(TextFieldValue("SELECT * FROM ")) }
    var queryResult by remember { mutableStateOf<QueryResult?>(null) }
    var isExecuting by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var showSuggestions by remember { mutableStateOf(false) }
    var suggestions by remember { mutableStateOf<List<SQLSuggestion>>(emptyList()) }
    var tables by remember { mutableStateOf<List<String>>(emptyList()) }
    var databases by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedTable by remember { mutableStateOf<String?>(null) }
    var showTableDropdown by remember { mutableStateOf(false) }
    
    // 查询历史和模板
    var queryHistory by remember { mutableStateOf<List<String>>(emptyList()) }
    var queryTemplates by remember { mutableStateOf<List<QueryTemplate>>(emptyList()) }
    var showHistoryDialog by remember { mutableStateOf(false) }
    var showTemplatesDialog by remember { mutableStateOf(false) }
    var showExportDialog by remember { mutableStateOf(false) }
    var showSettingsDialog by remember { mutableStateOf(false) }
    
    // 错误处理和性能监控
    var errorHandlingResult by remember { mutableStateOf<ErrorHandlingResult?>(null) }
    var showPerformanceDialog by remember { mutableStateOf(false) }
    var queryStartTime by remember { mutableStateOf(0L) }
    var showCacheStats by remember { mutableStateOf(false) }

    // 获取表的列信息
    var tableColumns by remember { mutableStateOf<Map<String, List<String>>>(emptyMap()) }
    
    // 加载表的列信息
    LaunchedEffect(tables) {
        if (tables.isNotEmpty()) {
            val columnsMap = mutableMapOf<String, List<String>>()
            tables.forEach { table ->
                val result = mysqlManager.executeQuery(databaseName, "DESCRIBE `$table`")
                if (result.isSuccess) {
                    val columns = result.getOrNull()?.rows?.map { it[0] } ?: emptyList()
                    columnsMap[table] = columns
                }
            }
            tableColumns = columnsMap
        }
    }
    
    // 更新智能提示函数
    fun updateSuggestions(query: String) {
        val cursorPosition = sqlQuery.selection.start
        val currentWord = getCurrentWordAtCursor(query, cursorPosition)
        val beforeCursor = query.substring(0, cursorPosition).uppercase()
        
        val smartSuggestions = smartSQLHelper.getContextualSuggestions(
            query, cursorPosition, tables, tableColumns, queryHistory
        )
        
        val additionalSuggestions = mutableListOf<SQLSuggestion>()
        
        // 检查是否在 FROM 或 JOIN 后面，如果是则提示表名
        if (beforeCursor.contains("FROM ") || beforeCursor.contains("JOIN ")) {
            tables.filter { it.contains(currentWord, ignoreCase = true) }.forEach {
                additionalSuggestions.add(SQLSuggestion("`$it`", "table", "表名", 0.9f))
            }
        }
        
        // 如果查询中包含 USE，建议数据库名
        if (beforeCursor.contains("USE ")) {
            databases.filter { it.contains(currentWord, ignoreCase = true) }.forEach {
                additionalSuggestions.add(SQLSuggestion("`$it`", "database", "数据库", 0.9f))
            }
        }
        
        // 合并建议
        val allSuggestions = (smartSuggestions + additionalSuggestions).distinctBy { it.text }
        
        suggestions = allSuggestions.take(15)
        showSuggestions = suggestions.isNotEmpty() && query.isNotEmpty()
    }

    // 保存查询到历史记录
    fun saveQueryToHistory(query: String) {
        val trimmedQuery = query.trim()
        if (trimmedQuery.isNotEmpty() && trimmedQuery.length > 10) {
            val updatedHistory = (listOf(trimmedQuery) + queryHistory)
                .distinct()
                .take(userPreferences.maxHistorySize)
            queryHistory = updatedHistory
            preferencesManager.saveQueryHistory(databaseName, updatedHistory)
        }
    }

    // 加载初始数据
    LaunchedEffect(Unit) {
        // 加载数据库列表
        val dbResult = mysqlManager.listDatabases()
        if (dbResult.isSuccess) {
            databases = dbResult.getOrNull() ?: emptyList()
        }
        
        // 只有在指定了数据库时才加载表列表
        if (databaseName.isNotBlank()) {
            val result = mysqlManager.listTables(databaseName)
            if (result.isSuccess) {
                tables = result.getOrNull() ?: emptyList()
            }
        }
        
        // 加载查询历史和模板
        queryHistory = preferencesManager.getQueryHistory(databaseName)
        queryTemplates = preferencesManager.getQueryTemplates()
    }

    // 智能提示更新
    LaunchedEffect(sqlQuery.text) {
        if (sqlQuery.text.isNotEmpty()) {
            updateSuggestions(sqlQuery.text)
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("查询 - $databaseName") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    // 查询模板按钮
                    IconButton(onClick = { showTemplatesDialog = true }) {
                        Icon(Icons.Default.Code, contentDescription = "查询模板")
                    }

                    // 查询历史按钮
                    IconButton(onClick = { showHistoryDialog = true }) {
                        Icon(Icons.Default.History, contentDescription = "查询历史")
                    }

                    // 性能监控按钮
                    IconButton(onClick = { showPerformanceDialog = true }) {
                        Icon(Icons.Default.Analytics, contentDescription = "性能监控")
                    }

                    // 导出按钮
                    if (queryResult != null) {
                        IconButton(onClick = { showExportDialog = true }) {
                            Icon(Icons.Default.Download, contentDescription = "导出数据")
                        }
                    }

                    // 设置按钮
                    IconButton(onClick = { showSettingsDialog = true }) {
                        Icon(Icons.Default.Settings, contentDescription = "设置")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            // SQL输入区域
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "SQL 查询",
                            style = MaterialTheme.typography.titleMedium
                        )

                        Row {
                            // 执行按钮
                            IconButton(
                                onClick = {
                                    if (sqlQuery.text.isNotBlank()) {
                                        isExecuting = true
                                        errorMessage = null
                                        queryResult = null
                                        errorHandlingResult = null
                                        showSuggestions = false
                                        queryStartTime = System.currentTimeMillis()

                                        saveQueryToHistory(sqlQuery.text)

                                        (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                                            // 检查缓存
                                            if (userPreferences.enableQueryCache) {
                                                val cachedResult = queryCache.get(sqlQuery.text, databaseName)
                                                if (cachedResult != null) {
                                                    queryResult = cachedResult
                                                    isExecuting = false
                                                    return@launch
                                                }
                                            }

                                            val result = mysqlManager.executeQuery(databaseName, sqlQuery.text)
                                            val executionTime = System.currentTimeMillis() - queryStartTime
                                            isExecuting = false

                                            if (result.isSuccess) {
                                                val resultData = result.getOrNull()!!
                                                queryResult = resultData
                                                errorMessage = null
                                                errorHandlingResult = null

                                                // 缓存结果
                                                if (userPreferences.enableQueryCache) {
                                                    queryCache.put(sqlQuery.text, databaseName, resultData)
                                                }

                                                // 记录性能
                                                if (userPreferences.enablePerformanceMonitor) {
                                                    performanceMonitor.recordQuery(
                                                        sqlQuery.text,
                                                        executionTime,
                                                        resultData.rows.size
                                                    )
                                                }
                                            } else {
                                                val error = result.exceptionOrNull()!!
                                                errorHandlingResult = smartErrorHandler.handleError(error, "查询执行")
                                                errorMessage = errorHandlingResult?.suggestion

                                                if (errorMessage?.contains("会话已过期") == true) {
                                                    onSessionExpired?.invoke()
                                                }

                                                // 自动重试
                                                if (errorHandlingResult?.autoRetry == true) {
                                                    delay(errorHandlingResult?.retryDelay ?: 1000L)
                                                    val retryResult = mysqlManager.executeQuery(databaseName, sqlQuery.text)
                                                    if (retryResult.isSuccess) {
                                                        queryResult = retryResult.getOrNull()
                                                        errorMessage = null
                                                        errorHandlingResult = null
                                                    }
                                                }
                                            }
                                        }
                                    }
                                },
                                enabled = !isExecuting && sqlQuery.text.isNotBlank()
                            ) {
                                if (isExecuting) {
                                    CircularProgressIndicator(modifier = Modifier.size(20.dp))
                                } else {
                                    Icon(Icons.Default.PlayArrow, contentDescription = "执行")
                                }
                            }

                            // 清空按钮
                            IconButton(
                                onClick = {
                                    sqlQuery = TextFieldValue("")
                                    queryResult = null
                                    errorMessage = null
                                    errorHandlingResult = null
                                    showSuggestions = false
                                }
                            ) {
                                Icon(Icons.Default.Clear, contentDescription = "清空")
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(8.dp))

                    // SQL输入框
                    OutlinedTextField(
                        value = sqlQuery,
                        onValueChange = {
                            sqlQuery = it
                            if (it.text.isNotEmpty()) {
                                updateSuggestions(it.text)
                            } else {
                                showSuggestions = false
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(120.dp),
                        placeholder = { Text("输入 SQL 查询语句...") },
                        textStyle = TextStyle(
                            fontFamily = FontFamily.Monospace,
                            fontSize = userPreferences.fontSize.sp
                        )
                    )

                    // 智能提示
                    if (showSuggestions && suggestions.isNotEmpty()) {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(max = 200.dp),
                            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                        ) {
                            LazyColumn {
                                items(suggestions) { suggestion ->
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .clickable {
                                                val currentText = sqlQuery.text
                                                val cursorPos = sqlQuery.selection.start
                                                val wordStart = getCurrentWordStart(currentText, cursorPos)
                                                val newText = currentText.substring(0, wordStart) +
                                                            suggestion.text +
                                                            currentText.substring(cursorPos)
                                                sqlQuery = TextFieldValue(
                                                    newText,
                                                    TextRange(wordStart + suggestion.text.length)
                                                )
                                                showSuggestions = false
                                            }
                                            .padding(horizontal = 16.dp, vertical = 8.dp),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        // 建议类型图标
                                        Icon(
                                            imageVector = when (suggestion.type) {
                                                "keyword" -> Icons.Default.Code
                                                "table" -> Icons.Default.TableChart
                                                "column" -> Icons.Default.ViewColumn
                                                "function" -> Icons.Default.Functions
                                                "history" -> Icons.Default.History
                                                "snippet" -> Icons.Default.AutoAwesome
                                                else -> Icons.Default.Lightbulb
                                            },
                                            contentDescription = null,
                                            modifier = Modifier.size(16.dp),
                                            tint = MaterialTheme.colorScheme.primary
                                        )

                                        Spacer(modifier = Modifier.width(8.dp))

                                        Column(modifier = Modifier.weight(1f)) {
                                            Text(
                                                text = suggestion.text,
                                                style = TextStyle(fontFamily = FontFamily.Monospace),
                                                fontSize = 14.sp
                                            )
                                            Text(
                                                text = suggestion.description,
                                                style = MaterialTheme.typography.bodySmall,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 结果显示区域
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "查询结果",
                        style = MaterialTheme.typography.titleMedium
                    )

                    Spacer(modifier = Modifier.height(8.dp))

                    when {
                        errorHandlingResult != null -> {
                            errorHandlingResult?.let { errorResult ->
                                Card(
                                    colors = CardDefaults.cardColors(
                                        containerColor = MaterialTheme.colorScheme.errorContainer
                                    )
                                ) {
                                    Column(modifier = Modifier.padding(16.dp)) {
                                        Text(
                                            text = "错误类型: ${errorResult.errorType}",
                                            color = MaterialTheme.colorScheme.onErrorContainer,
                                            style = MaterialTheme.typography.titleSmall
                                        )
                                        Spacer(modifier = Modifier.height(8.dp))
                                        SelectionContainer {
                                            Text(
                                                text = errorResult.suggestion,
                                                color = MaterialTheme.colorScheme.onErrorContainer,
                                                fontFamily = FontFamily.Monospace
                                            )
                                        }
                                        Spacer(modifier = Modifier.height(8.dp))
                                        Text(
                                            text = "建议操作: ${errorResult.userAction}",
                                            color = MaterialTheme.colorScheme.onErrorContainer,
                                            style = MaterialTheme.typography.bodySmall
                                        )

                                        // SQL优化建议
                                        val optimizations = smartErrorHandler.getSQLOptimizationSuggestions(
                                            sqlQuery.text,
                                            errorResult.suggestion
                                        )
                                        if (optimizations.isNotEmpty()) {
                                            Spacer(modifier = Modifier.height(8.dp))
                                            Text(
                                                text = "优化建议:",
                                                color = MaterialTheme.colorScheme.onErrorContainer,
                                                style = MaterialTheme.typography.titleSmall
                                            )
                                            optimizations.forEach { suggestion ->
                                                Text(
                                                    text = "• $suggestion",
                                                    color = MaterialTheme.colorScheme.onErrorContainer,
                                                    style = MaterialTheme.typography.bodySmall
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        queryResult != null -> {
                            QueryResultTable(queryResult!!)
                        }
                        else -> {
                            Text(
                                text = "请输入 SQL 查询并点击执行",
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }
    }

    // 查询模板对话框
    if (showTemplatesDialog) {
        AlertDialog(
            onDismissRequest = { showTemplatesDialog = false },
            title = { Text("查询模板") },
            text = {
                LazyColumn {
                    items(queryTemplates) { template ->
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp)
                                .clickable {
                                    sqlQuery = TextFieldValue(template.template) // 直接替换，不追加
                                    showTemplatesDialog = false
                                    showSuggestions = false // 关闭智能提示
                                }
                        ) {
                            Column(modifier = Modifier.padding(12.dp)) {
                                Text(
                                    text = template.name,
                                    style = MaterialTheme.typography.titleSmall
                                )
                                Text(
                                    text = template.template.take(50) + "...",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showTemplatesDialog = false }) {
                    Text("关闭")
                }
            }
        )
    }

    // 查询历史对话框
    if (showHistoryDialog) {
        AlertDialog(
            onDismissRequest = { showHistoryDialog = false },
            title = { Text("查询历史") },
            text = {
                LazyColumn {
                    items(queryHistory) { query ->
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp)
                                .clickable {
                                    sqlQuery = TextFieldValue(query) // 直接替换，不追加
                                    showHistoryDialog = false
                                    showSuggestions = false // 关闭智能提示
                                }
                        ) {
                            Text(
                                text = query.take(100) + if (query.length > 100) "..." else "",
                                modifier = Modifier.padding(12.dp),
                                style = TextStyle(fontFamily = FontFamily.Monospace),
                                fontSize = 12.sp
                            )
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showHistoryDialog = false }) {
                    Text("关闭")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        queryHistory = emptyList()
                        preferencesManager.clearQueryHistory(databaseName)
                        showHistoryDialog = false
                    }
                ) {
                    Text("清空历史")
                }
            }
        )
    }

    // 性能监控对话框
    if (showPerformanceDialog) {
        AlertDialog(
            onDismissRequest = { showPerformanceDialog = false },
            title = { Text("性能监控") },
            text = {
                Column {
                    // 缓存统计
                    val cacheStats = queryCache.getCacheStats()
                    Text("查询缓存统计:")
                    Text("• 命中率: ${(cacheStats.hitRate * 100).toInt()}%")
                    Text("• 缓存大小: ${cacheStats.size}/${cacheStats.maxSize}")

                    Spacer(modifier = Modifier.height(16.dp))

                    // 慢查询
                    Text("慢查询 (>1秒):")
                    val slowQueries = performanceMonitor.getSlowQueries()
                    if (slowQueries.isEmpty()) {
                        Text("• 暂无慢查询")
                    } else {
                        slowQueries.take(3).forEach { query ->
                            Text(
                                "• ${query.query.take(50)}... (${query.avgTime}ms)",
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }

                    Spacer(modifier = Modifier.height(16.dp))

                    // 连接池状态
                    LaunchedEffect(Unit) {
                        val poolStats = mysqlManager.getConnectionPoolStats()
                        // 显示连接池统计
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showPerformanceDialog = false }) {
                    Text("关闭")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        queryCache.clear()
                        performanceMonitor.clearMetrics()
                        showPerformanceDialog = false
                    }
                ) {
                    Text("清空数据")
                }
            }
        )
    }

    // 添加文件选择器相关状态
    var showPathSelectionDialog by remember { mutableStateOf(false) }
    var selectedExportFormat by remember { mutableStateOf("") }
    var availableExportPaths by remember { mutableStateOf<List<ExportPath>>(emptyList()) }

    // 文件选择器启动器
    val documentPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.CreateDocument("*/*")
    ) { uri ->
        if (uri != null && queryResult != null) {
            (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                try {
                    val exportResult = dataExporter.exportToUri(
                        context,
                        queryResult!!,
                        selectedExportFormat,
                        uri
                    )

                    if (exportResult.isSuccess) {
                        Toast.makeText(
                            context,
                            "导出成功！",
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        Toast.makeText(
                            context,
                            "导出失败: ${exportResult.exceptionOrNull()?.message}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } catch (e: Exception) {
                    Toast.makeText(
                        context,
                        "导出异常: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }

    // 数据导出对话框
    if (showExportDialog && queryResult != null) {
        AlertDialog(
            onDismissRequest = { showExportDialog = false },
            title = { Text("导出数据") },
            text = {
                Column {
                    Text("选择导出格式:")
                    Spacer(modifier = Modifier.height(8.dp))

                    listOf("CSV", "JSON", "XML", "Excel").forEach { format ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    selectedExportFormat = format
                                    availableExportPaths = dataExporter.getAvailableExportPaths(context)
                                    showExportDialog = false
                                    showPathSelectionDialog = true
                                }
                                .padding(8.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(format)
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showExportDialog = false }) {
                    Text("取消")
                }
            }
        )
    }

    // 路径选择对话框
    if (showPathSelectionDialog) {
        AlertDialog(
            onDismissRequest = { showPathSelectionDialog = false },
            title = { Text("选择保存位置") },
            text = {
                LazyColumn {
                    items(availableExportPaths) { exportPath ->
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp)
                                .clickable(enabled = exportPath.isWritable) {
                                    if (exportPath.isWritable) {
                                        (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                                            try {
                                                val exportResult = dataExporter.exportToFile(
                                                    context,
                                                    queryResult!!,
                                                    selectedExportFormat,
                                                    customPath = exportPath.path
                                                )

                                                if (exportResult.isSuccess) {
                                                    val filePath = exportResult.getOrNull()!!
                                                    Toast.makeText(
                                                        context,
                                                        "导出成功！\n文件保存至: $filePath",
                                                        Toast.LENGTH_LONG
                                                    ).show()
                                                } else {
                                                    Toast.makeText(
                                                        context,
                                                        "导出失败: ${exportResult.exceptionOrNull()?.message}",
                                                        Toast.LENGTH_SHORT
                                                    ).show()
                                                }
                                            } catch (e: Exception) {
                                                Toast.makeText(
                                                    context,
                                                    "导出异常: ${e.message}",
                                                    Toast.LENGTH_SHORT
                                                ).show()
                                            }
                                        }
                                        showPathSelectionDialog = false
                                    }
                                },
                            colors = CardDefaults.cardColors(
                                containerColor = if (exportPath.isWritable)
                                    MaterialTheme.colorScheme.surface
                                else
                                    MaterialTheme.colorScheme.surfaceVariant
                            )
                        ) {
                            Column(modifier = Modifier.padding(12.dp)) {
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Text(
                                        text = exportPath.displayName,
                                        style = MaterialTheme.typography.titleSmall,
                                        color = if (exportPath.isWritable)
                                            MaterialTheme.colorScheme.onSurface
                                        else
                                            MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                    if (!exportPath.isWritable) {
                                        Icon(
                                            Icons.Default.Lock,
                                            contentDescription = "无权限",
                                            tint = MaterialTheme.colorScheme.error,
                                            modifier = Modifier.size(16.dp)
                                        )
                                    }
                                }
                                Text(
                                    text = exportPath.description,
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                                Text(
                                    text = exportPath.path,
                                    style = MaterialTheme.typography.bodySmall,
                                    fontFamily = FontFamily.Monospace,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }

                    item {
                        Spacer(modifier = Modifier.height(8.dp))
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    val intent = dataExporter.createDocumentIntent(selectedExportFormat)
                                    documentPickerLauncher.launch(intent.getStringExtra(Intent.EXTRA_TITLE) ?: "export")
                                    showPathSelectionDialog = false
                                }
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(12.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(Icons.Default.FolderOpen, contentDescription = null)
                                Spacer(modifier = Modifier.width(8.dp))
                                Column {
                                    Text(
                                        text = "选择其他位置",
                                        style = MaterialTheme.typography.titleSmall
                                    )
                                    Text(
                                        text = "使用系统文件选择器",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showPathSelectionDialog = false }) {
                    Text("取消")
                }
            }
        )
    }

    // 设置对话框
    if (showSettingsDialog) {
        AlertDialog(
            onDismissRequest = { showSettingsDialog = false },
            title = { Text("查询设置") },
            text = {
                Column {
                    // 查询超时设置
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("查询超时 (秒)")
                        Text("${userPreferences.queryTimeout}")
                    }

                    // 缓存开关
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("启用查询缓存")
                        Switch(
                            checked = userPreferences.enableQueryCache,
                            onCheckedChange = { userPreferences.enableQueryCache = it }
                        )
                    }

                    // 性能监控开关
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("启用性能监控")
                        Switch(
                            checked = userPreferences.enablePerformanceMonitor,
                            onCheckedChange = { userPreferences.enablePerformanceMonitor = it }
                        )
                    }

                    // 自动保存查询
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text("自动保存查询")
                        Switch(
                            checked = userPreferences.autoSaveQueries,
                            onCheckedChange = { userPreferences.autoSaveQueries = it }
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showSettingsDialog = false }) {
                    Text("确定")
                }
            }
        )
    }
}

@Composable
fun QueryResultTable(result: QueryResult) {
    var selectedRowIndex by remember { mutableStateOf<Int?>(null) }
    var showContentDialog by remember { mutableStateOf(false) }
    var dialogContent by remember { mutableStateOf("") }
    var dialogTitle by remember { mutableStateOf("") }
    var currentPage by remember { mutableStateOf(1) }
    var sortColumn by remember { mutableStateOf<String?>(null) }
    var sortAscending by remember { mutableStateOf(true) }
    var filterText by remember { mutableStateOf("") }
    var showFilterDialog by remember { mutableStateOf(false) }

    val pageSize = 20

    // 过滤和排序数据
    val filteredRows = remember(result.rows, filterText) {
        if (filterText.isBlank()) {
            result.rows
        } else {
            result.rows.filter { row ->
                row.any { cell -> cell.contains(filterText, ignoreCase = true) }
            }
        }
    }

    val sortedRows = remember(filteredRows, sortColumn, sortAscending) {
        if (sortColumn == null) {
            filteredRows
        } else {
            val columnIndex = result.columns.indexOf(sortColumn)
            if (columnIndex >= 0) {
                filteredRows.sortedWith { row1, row2 ->
                    val value1 = if (columnIndex < row1.size) row1[columnIndex] else ""
                    val value2 = if (columnIndex < row2.size) row2[columnIndex] else ""
                    if (sortAscending) value1.compareTo(value2) else value2.compareTo(value1)
                }
            } else {
                filteredRows
            }
        }
    }

    val totalRows = sortedRows.size
    val totalPages = (totalRows + pageSize - 1) / pageSize
    val startIndex = (currentPage - 1) * pageSize
    val endIndex = minOf(startIndex + pageSize, totalRows)
    val displayRows = if (totalRows > 0) sortedRows.subList(startIndex, endIndex) else emptyList()

    Column {
        // 统一的消息显示 - 只显示一次
        if (result.message.isNotEmpty()) {
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer
                ),
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = result.message,
                    modifier = Modifier.padding(16.dp),
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            Spacer(modifier = Modifier.height(8.dp))
        }

        // 工具栏 - 只在有查询数据时显示
        if (result.columns.isNotEmpty() && result.rows.isNotEmpty()) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "查询结果 - 共 $totalRows 行",
                    style = MaterialTheme.typography.titleMedium
                )

                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 筛选按钮
                    IconButton(onClick = { showFilterDialog = true }) {
                        Icon(
                            Icons.Default.FilterList,
                            contentDescription = "筛选",
                            tint = if (filterText.isNotBlank()) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                        )
                    }

                    // 分页控制
                    if (totalPages > 1) {
                        IconButton(
                            onClick = { if (currentPage > 1) currentPage-- },
                            enabled = currentPage > 1
                        ) {
                            Icon(Icons.Default.ChevronLeft, contentDescription = "上一页")
                        }

                        Text(
                            text = "$currentPage/$totalPages",
                            style = MaterialTheme.typography.bodyMedium
                        )

                        IconButton(
                            onClick = { if (currentPage < totalPages) currentPage++ },
                            enabled = currentPage < totalPages
                        ) {
                            Icon(Icons.Default.ChevronRight, contentDescription = "下一页")
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))
        }

        // 表格数据显示
        if (result.columns.isNotEmpty() && displayRows.isNotEmpty()) {
            LazyColumn(
                modifier = Modifier.fillMaxSize()
            ) {
                item {
                    LazyRow {
                        items(result.columns.indices.toList()) { columnIndex ->
                            Column {
                                // 表头
                                Card(
                                    modifier = Modifier
                                        .width(150.dp)
                                        .height(48.dp)
                                        .padding(1.dp)
                                        .clickable {
                                            val column = result.columns[columnIndex]
                                            if (sortColumn == column) {
                                                sortAscending = !sortAscending
                                            } else {
                                                sortColumn = column
                                                sortAscending = true
                                            }
                                            currentPage = 1
                                        },
                                    colors = CardDefaults.cardColors(
                                        containerColor = MaterialTheme.colorScheme.primaryContainer
                                    )
                                ) {
                                    Box(
                                        modifier = Modifier.fillMaxSize(),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.spacedBy(4.dp)
                                        ) {
                                            Text(
                                                text = result.columns[columnIndex],
                                                style = MaterialTheme.typography.labelMedium,
                                                color = MaterialTheme.colorScheme.onPrimaryContainer,
                                                maxLines = 1,
                                                overflow = TextOverflow.Ellipsis
                                            )
                                            if (sortColumn == result.columns[columnIndex]) {
                                                Icon(
                                                    if (sortAscending) Icons.Default.ArrowUpward else Icons.Default.ArrowDownward,
                                                    contentDescription = null,
                                                    modifier = Modifier.size(12.dp),
                                                    tint = MaterialTheme.colorScheme.onPrimaryContainer
                                                )
                                            }
                                        }
                                    }
                                }

                                // 该列的所有数据
                                displayRows.forEachIndexed { rowIndex, row ->
                                    val actualRowIndex = startIndex + rowIndex
                                    val cellContent = if (columnIndex < row.size) row[columnIndex] else ""

                                    Card(
                                        modifier = Modifier
                                            .width(150.dp)
                                            .height(48.dp)
                                            .padding(1.dp)
                                            .combinedClickable(
                                                onClick = {
                                                    selectedRowIndex = if (selectedRowIndex == actualRowIndex) null else actualRowIndex
                                                },
                                                onDoubleClick = {
                                                    dialogContent = cellContent
                                                    dialogTitle = "${result.columns[columnIndex]} (第${actualRowIndex + 1}行)"
                                                    showContentDialog = true
                                                }
                                            ),
                                        colors = CardDefaults.cardColors(
                                            containerColor = if (selectedRowIndex == actualRowIndex)
                                                MaterialTheme.colorScheme.secondaryContainer
                                            else
                                                MaterialTheme.colorScheme.surface
                                        )
                                    ) {
                                        Box(
                                            modifier = Modifier.fillMaxSize(),
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = cellContent,
                                                modifier = Modifier.padding(8.dp),
                                                style = MaterialTheme.typography.bodySmall,
                                                fontFamily = FontFamily.Monospace,
                                                color = if (selectedRowIndex == actualRowIndex)
                                                    MaterialTheme.colorScheme.onSecondaryContainer
                                                else
                                                    MaterialTheme.colorScheme.onSurface,
                                                maxLines = 1,
                                                overflow = TextOverflow.Ellipsis
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (result.columns.isNotEmpty()) {
            Text(
                text = "没有匹配的数据",
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(16.dp)
            )
        }

        // 筛选对话框
        if (showFilterDialog) {
            var tempFilterText by remember { mutableStateOf(filterText) }

            AlertDialog(
                onDismissRequest = { showFilterDialog = false },
                title = { Text("筛选数据") },
                text = {
                    OutlinedTextField(
                        value = tempFilterText,
                        onValueChange = { tempFilterText = it },
                        label = { Text("筛选条件") },
                        placeholder = { Text("输入关键词筛选所有列") },
                        modifier = Modifier.fillMaxWidth()
                    )
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            filterText = tempFilterText
                            currentPage = 1
                            showFilterDialog = false
                        }
                    ) {
                        Text("应用")
                    }
                },
                dismissButton = {
                    TextButton(
                        onClick = {
                            tempFilterText = ""
                            filterText = ""
                            currentPage = 1
                            showFilterDialog = false
                        }
                    ) {
                        Text("清除")
                    }
                }
            )
        }

        // 内容详情弹窗
        if (showContentDialog) {
            AlertDialog(
                onDismissRequest = { showContentDialog = false },
                title = { Text(dialogTitle) },
                text = {
                    SelectionContainer {
                        Text(
                            text = dialogContent,
                            fontFamily = FontFamily.Monospace,
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                },
                confirmButton = {
                    TextButton(onClick = { showContentDialog = false }) {
                        Text("关闭")
                    }
                }
            )
        }
    }
}

// 辅助函数
fun getCurrentWordStart(text: String, cursorPosition: Int): Int {
    var start = cursorPosition - 1
    while (start >= 0 && text[start].isLetterOrDigit()) {
        start--
    }
    return start + 1
}

fun getCurrentWordAtCursor(text: String, cursorPosition: Int): String {
    if (cursorPosition <= 0 || cursorPosition > text.length) return ""
    
    var start = cursorPosition - 1
    while (start >= 0 && (text[start].isLetterOrDigit() || text[start] == '_')) {
        start--
    }
    start++
    
    var end = cursorPosition
    while (end < text.length && (text[end].isLetterOrDigit() || text[end] == '_')) {
        end++
    }
    
    return if (start < end) text.substring(start, end) else ""
}
